﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StartupTaskRunner.Configuration;
using StartupTaskRunner.Logging;
using StartupTaskRunner.Actions;
using System.Diagnostics.Contracts;

namespace StartupTaskRunner
{
    public class StartupTaskRunner
    {
        public ConfigType Configuration { get; set; }

        public StartupTaskRunner() { }

        public StartupTaskRunner(ConfigType configuration)
        {
            Configuration = configuration;
        }

        /// <summary>
        /// Executes all tasks in the list of tasks with the given configuration
        /// </summary>
        /// <param name="configuration">configuration</param>
        public void Execute(ConfigType configuration)
        {
            Configuration = configuration;
            Execute();
        }

        /// <summary>
        /// Executes all tasks in the list of tasks
        /// </summary>
        public void Execute()
        {
            if (Configuration == null)
            {
                throw new ApplicationException("Missing configuration.");
            }

            ExecuteTasks();
        }

        private void ExecuteTasks()
        {
            // The tasks are just a container for the actions

            foreach (TaskType task in Configuration.Tasks)
            {
                    if (task.Items != null)
                    {
                        using (new LogContext(task.name))
                        {
                            List<IAction> actionsToExecute = ActionFactory.GetActions(task.Items, Configuration);

                            int step = 0;
                            foreach (var action in actionsToExecute)
                            {
                                string name = string.Format("step: {0} [{1}]", ++step, action.Type);
                                using (new LogContext(name))
                                {
                                    action.Execute();
                                }
                            }
                        }
                    }
                    else
                    {
                        Logger.WriteMessage("Warning: Task {0} has no steps defined", task.name);
                    }
                }
        }
    }
}
